package com.shark.demo;

import lombok.Data;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName SaleTicket
 * @Description TODO
 * @Author 东北彭于晏
 * @Date 2024/9/2821:05
 * @Version 1.0
 **/
public class SaleTicket {
    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        ticket.setTicketNumber(50);

        new Thread(() -> {
            for (int i = 0; i < 25; i++) {
                ticket.saleTicket();
            }
        }, "窗口1").start();

        new Thread(() -> {
            for (int i = 0; i < 25; i++) {
                ticket.saleTicket();
            }
        }, "窗口2").start();
    }

}


@Data
class Ticket {
    private Integer ticketNumber;
    //公平锁可以交替
    Lock lock = new ReentrantLock();

    public void saleTicket() {
        lock.lock();
        try {
            if (ticketNumber > 0) {
                System.out.println(Thread.currentThread().getName() + "卖出 :" + (ticketNumber--) + "-------还剩 :" + ticketNumber);
                TimeUnit.MILLISECONDS.sleep(10);
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

}